/*
 * Copyright 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.keyczar.rsa;

import static org.keyczar.util.Util.decodeBigInteger;
import static org.keyczar.util.Util.encodeBigInteger;

import com.google.gson.annotations.Expose;

import org.keyczar.DefaultKeyType;
import org.keyczar.KeyczarKey;
import org.keyczar.KeyczarPrivateKey;
import org.keyczar.KeyczarPublicKey;
import org.keyczar.exceptions.KeyczarException;
import org.keyczar.interfaces.KeyType;
import org.keyczar.interfaces.Stream;
import org.keyczar.keyparams.RsaSigningKeyParameters;
import org.keyczar.util.Util;

import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.Signature;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.RSAPrivateCrtKeySpec;

/**
 * Wrapping class for RSA Private Keys suitable for signing
 *
 * @author steveweis@gmail.com (Steve Weis)
 * @author arkajit.dey@gmail.com (Arkajit Dey)
 */
public class RsaPrivateSigningKey extends KeyczarKey implements KeyczarPrivateKey {
  private static final String KEY_GEN_ALGORITHM = "RSA";

  @Expose private final RsaPublicSigningKey publicKey;
  @Expose private final String privateExponent;
  @Expose private final String primeP;
  @Expose private final String primeQ;
  @Expose private final String primeExponentP;
  @Expose private final String primeExponentQ;
  @Expose private final String crtCoefficient;
  @Expose private final String signatureAlgorithm;
  @Expose private final String mgf;

  private RSAPrivateCrtKey jcePrivateKey;

  public static RsaPrivateSigningKey generate(RsaSigningKeyParameters params) throws KeyczarException {
    KeyPair keyPair = Util.generateKeyPair(KEY_GEN_ALGORITHM, params.getKeySize());
    return new RsaPrivateSigningKey((RSAPrivateCrtKey) keyPair.getPrivate(),
        params.getSignatureAlgorithm(), params.getMgf());
  }

  public static RsaPrivateSigningKey read(String input) throws KeyczarException {
    RsaPrivateSigningKey key = Util.gson().fromJson(input, RsaPrivateSigningKey.class);
    return key.initFromJson();
  }

  RsaPrivateSigningKey(RSAPrivateCrtKey privateKey, String signatureAlgorithm, String mgf) throws KeyczarException {
    super(privateKey.getModulus().bitLength());
    publicKey = new RsaPublicSigningKey(privateKey, signatureAlgorithm, mgf);
    privateExponent = encodeBigInteger(privateKey.getPrivateExponent());
    primeP = encodeBigInteger(privateKey.getPrimeP());
    primeQ = encodeBigInteger(privateKey.getPrimeQ());
    primeExponentP = encodeBigInteger(privateKey.getPrimeExponentP());
    primeExponentQ = encodeBigInteger(privateKey.getPrimeExponentQ());
    crtCoefficient = encodeBigInteger(privateKey.getCrtCoefficient());
    jcePrivateKey = privateKey;
    this.signatureAlgorithm = signatureAlgorithm;
    this.mgf = mgf;
  }

  private RsaPrivateSigningKey() {
    super(0);
    publicKey = null;
    privateExponent = null;
    primeP = null;
    primeQ = null;
    primeExponentP = null;
    primeExponentQ = null;
    crtCoefficient = null;
    jcePrivateKey = null;
    signatureAlgorithm = null;
    mgf = null;
  }

  @Override
  protected Stream getStream() throws KeyczarException {
    try {
      return new RsaSigningStream(Signature.getInstance(
          SignatureAlgorithm.getSignatureAlgorithm(signatureAlgorithm, mgf)), 
          jcePrivateKey, publicKey.getJceKey());
    } catch (GeneralSecurityException ex) {
      throw new KeyczarException(ex);
    }
  }

  @Override
  public KeyType getType() {
    return DefaultKeyType.RSA_PRIV;
  }

  @Override
  protected byte[] hash() {
    return publicKey.hash();
  }

  @Override
  public KeyczarPublicKey getPublic() {
    return publicKey;
  }

  /**
   * Initialize JCE key from JSON data.  Must be called after an instance is read from JSON.
   */
  private RsaPrivateSigningKey initFromJson() throws KeyczarException {
    publicKey.initFromJson();
    try {
      final KeyFactory keyFactory = KeyFactory.getInstance(KEY_GEN_ALGORITHM);
      final RSAPrivateCrtKeySpec spec =
          new RSAPrivateCrtKeySpec(decodeBigInteger(publicKey.modulus),
            decodeBigInteger(publicKey.publicExponent), decodeBigInteger(privateExponent),
            decodeBigInteger(primeP), decodeBigInteger(primeQ), decodeBigInteger(primeExponentP),
            decodeBigInteger(primeExponentQ), decodeBigInteger(crtCoefficient));
      jcePrivateKey = (RSAPrivateCrtKey) keyFactory.generatePrivate(spec);
      return this;
    } catch (GeneralSecurityException e) {
      throw new KeyczarException(e);
    }
  }

  @Override
  protected RSAPrivateCrtKey getJceKey() {
    return jcePrivateKey;
  }
}
